import React, { useEffect, useState } from 'react';
import { Tabs, Swiper, Rate, Tag, Button, Toast, NavBar } from 'antd-mobile';
import { useThrottleFn } from 'ahooks';
import { useNavigate, useParams } from 'react-router-dom';
import { home } from '../../api/home'; // 改为导入home接口
import './goods.css';

const tabItems = [
  { key: '1', title: '商品' },
  { key: '2', title: '详情' },
  { key: '3', title: '评价' },
];

const tabHeight = 42;

export default function Goods() {
  const navigate = useNavigate();
  const { id } = useParams(); // 获取路径参数
  
  const [activeKey, setActiveKey] = useState('1');
  const [goodsData, setGoodsData] = useState(null);
  const [loading, setLoading] = useState(false);

  const { run: handleScroll } = useThrottleFn(
    () => {
      let currentKey = tabItems[0].key;
      for (const item of tabItems) {
        const element = document.getElementById(`anchor-${item.key}`);
        if (!element) continue;
        const rect = element.getBoundingClientRect();
        if (rect.top <= tabHeight) {
          currentKey = item.key;
        } else {
          break;
        }
      }
      setActiveKey(currentKey);
    },
    {
      leading: true,
      trailing: true,
      wait: 100,
    }
  );

  useEffect(() => {
    window.addEventListener('scroll', handleScroll);
    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  // 获取商品ID并请求数据
  useEffect(() => {
    const fetchGoodsData = async () => {
      // 从路径参数中获取商品ID
      const goodsId = id;
      
      console.log('商品ID:', goodsId); // 调试信息
      
      if (!goodsId) {
        Toast.show({
          icon: 'fail',
          content: '缺少商品ID参数',
        });
        return;
      }

      try {
        setLoading(true);
        // 调用首页接口获取所有数据
        const res = await home(); // 改为调用home接口
        
        console.log('API返回结果:', res); // 调试信息
        
        if (res.code === 200 && res.data) {
          // 在返回的商品数据中查找匹配的商品ID
          let matchedGoods = null;
          
          // 检查commodity数组中是否有匹配的商品
          if (res.data.commodity && Array.isArray(res.data.commodity)) {
            matchedGoods = res.data.commodity.find(item => 
              item.id && item.id.toString() === goodsId.toString()
            );
          }
          
          if (matchedGoods) {
            // 格式化数据以匹配页面结构
            const formattedData = {
              id: matchedGoods.id,
              name: matchedGoods.title || matchedGoods.name || '未知商品',
              price: matchedGoods.price ? parseFloat(matchedGoods.price) : 0,
              originalPrice: matchedGoods.original_price ? parseFloat(matchedGoods.original_price) : 
                           (matchedGoods.price ? parseFloat(matchedGoods.price) * 1.2 : 0),
              images: matchedGoods.image ? [matchedGoods.image] : [],
              description: matchedGoods.description || matchedGoods.title || '暂无商品描述',
              details: matchedGoods.detail_images ? matchedGoods.detail_images.split(',') : [],
              reviews: []
            };
            
            console.log('格式化后的数据:', formattedData); // 调试信息
            setGoodsData(formattedData);
          } else {
            Toast.show({
              icon: 'fail',
              content: '未找到匹配的商品',
            });
          }
        } else {
          Toast.show({
            icon: 'fail',
            content: res.message || '获取商品数据失败',
          });
        }
      } catch (error) {
        console.error('获取商品数据失败:', error);
        Toast.show({
          icon: 'fail',
          content: '获取商品数据失败: ' + error.message,
        });
      } finally {
        setLoading(false);
      }
    };

    if (id) {
      fetchGoodsData();
    }
  }, [id]);

  const handleTabChange = (key) => {
    const element = document.getElementById(`anchor-${key}`);
    if (element) {
      element.scrollIntoView();
      window.scrollTo({
        top: window.scrollY - tabHeight,
      });
    }
    setActiveKey(key);
  };

  // 渲染商品信息
  const renderGoodsInfo = () => {
    if (!goodsData) return null;
    
    return (
      <div className="goods-info">
        {/* 商品图片轮播 */}
        <div className="goods-swiper">
          <Swiper autoplay loop>
            {goodsData.images && goodsData.images.length > 0 ? (
              goodsData.images.map((image, index) => (
                <Swiper.Item key={index}>
                  <img 
                    src={image.startsWith('http') ? image : `http://jingxun.kuxia.top${image}`} 
                    alt={`商品图片${index + 1}`} 
                    className="goods-image" 
                  />
                </Swiper.Item>
              ))
            ) : (
              <Swiper.Item>
                <img 
                  src="https://via.placeholder.com/400x400?text=暂无图片" 
                  alt="默认图片" 
                  className="goods-image" 
                />
              </Swiper.Item>
            )}
          </Swiper>
        </div>
        
        {/* 商品基本信息 */}
        <div className="goods-basic-info">
          <h1 className="goods-title">{goodsData.name}</h1>
          <div className="goods-price">
            <span className="price-current">¥{goodsData.price.toFixed(2)}</span>
            {goodsData.originalPrice && goodsData.originalPrice > goodsData.price && (
              <span className="price-original">¥{goodsData.originalPrice.toFixed(2)}</span>
            )}
          </div>
          
          <div className="goods-tags">
            <Tag color="danger">限时特价</Tag>
            <Tag color="primary">包邮</Tag>
          </div>
        </div>
        
        {/* 商品规格 */}
        <div className="goods-specifications">
          <div className="spec-item">
            <span className="spec-label">规格:</span>
            <span className="spec-value">标准</span>
          </div>
          <div className="spec-item">
            <span className="spec-label">数量:</span>
            <span className="spec-value">1</span>
          </div>
        </div>
        
        {/* 操作按钮 */}
        <div className="goods-actions">
          <Button block color="primary" size="large">立即购买</Button>
          <Button block fill="outline" color="primary" size="large" style={{ marginTop: 10 }}>加入购物车</Button>
        </div>
      </div>
    );
  };

  // 渲染商品详情
  const renderGoodsDetails = () => {
    if (!goodsData) return null;
    
    return (
      <div className="goods-details">
        <h2>商品详情</h2>
        <p>{goodsData.description}</p>
        
        <h3>产品参数</h3>
        <div className="specifications-list">
          {goodsData.specifications.map((spec, index) => (
            <div className="spec-row" key={index}>
              <span className="spec-label">{spec.label}</span>
              <span className="spec-value">{spec.value}</span>
            </div>
          ))}
        </div>
        
        <h3>详情图片</h3>
        <div className="details-images">
          {goodsData.details && goodsData.details.length > 0 ? (
            goodsData.details.map((image, index) => (
              <img 
                key={index} 
                src={image.startsWith('http') ? image : `http://jingxun.kuxia.top${image}`} 
                alt={`详情图片${index + 1}`} 
                className="detail-image" 
              />
            ))
          ) : (
            <p>暂无详情图片</p>
          )}
        </div>
      </div>
    );
  };

  // 渲染评价信息
  const renderGoodsReviews = () => {
    if (!goodsData) return null;
    
    return (
      <div className="goods-reviews">
        <h2>用户评价</h2>
        <div className="reviews-summary">
          <div className="rating-score">
            <span className="score">5.0</span>
            <Rate allowHalf defaultValue={5} readOnly />
            <span className="review-count">暂无评价</span>
          </div>
        </div>
        
        <div className="reviews-list">
          <div className="no-reviews">暂无用户评价</div>
        </div>
      </div>
    );
  };

  // 渲染加载状态
  if (loading) {
    return <div className="loading">加载中...</div>;
  }

  // 检查ID是否存在
  if (!id) {
    return (
      <div>
        <NavBar onBack={() => navigate(-1)}>商品详情</NavBar>
        <div className="no-data">缺少商品ID</div>
      </div>
    );
  }

  return (
    <div>
      {/* 返回按钮 */}
      <NavBar onBack={() => navigate(-1)}>商品详情</NavBar>
      
      <div className="tabs-container">
        <Tabs
          activeKey={activeKey}
          onChange={handleTabChange}
        >
          {tabItems.map(item => (
            <Tabs.Tab title={item.title} key={item.key} />
          ))}
        </Tabs>
      </div>
      
      <div className="content">
        <div key="1">
          <h2 id="anchor-1"></h2>
          {goodsData ? renderGoodsInfo() : <div className="no-data">暂无商品数据</div>}
        </div>
        
        <div key="2">
          <h2 id="anchor-2"></h2>
          {goodsData ? renderGoodsDetails() : <div className="no-data">暂无详情数据</div>}
        </div>
        
        <div key="3">
          <h2 id="anchor-3"></h2>
          {renderGoodsReviews()}
        </div>
      </div>
    </div>
  );
}